package com.dongyimai.oauth.service.impl;

import com.dongyimai.oauth.service.AuthService;
import com.dongyimai.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     *
     * @param username  用户登录名
     * @param password   用户密码
     * @param client      配置文件中的客户端ID  通过Controller中读取配置文件
     * @param clientSecret   配置文件中的秘钥
     * @return
     */
    @Override
    public AuthToken login(String username, String password, String client, String clientSecret) {

        // 令牌的URL
        ServiceInstance instance = loadBalancerClient.choose("USER-AUTH");
        if(instance == null){
            throw new RuntimeException("找不到对应的服务");
        }
        String url = instance.getUri().toString() + "/oauth/token";
        System.out.println(url);
        // String url = "http://localhost:100001/oauth/token
        // 定义请求body
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        // 授权模式  password模式
        formData.add("grant_type","password");
        // 账号
        formData.add("username",username);
        // 密码
        formData.add("password",password);
        // 定义请求头
        // base64加密
        String authStr = client + ":" + clientSecret;
        byte[] encode = Base64.getEncoder().encode(authStr.getBytes());
        String headerValue = "Basic " + new String(encode);
        System.out.println(headerValue);
        // 定义头
        MultiValueMap<String, String> reqHeader = new LinkedMultiValueMap<>();
        reqHeader.add("Authorization",headerValue);
        // 发出请求
        ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(formData, reqHeader), Map.class);
        Map body = responseEntity.getBody();
        // 获取返回的数据
        AuthToken authToken = new AuthToken();
        authToken.setAccessToken((String)body.get("access_token"));
        authToken.setRefreshToken((String)body.get("refresh_token"));
        authToken.setJti((String)body.get("jti"));
        return authToken;
    }
}
